<template>
  <div class="table-box">
    <el-table
      ref="multipleTable"
      :data="tableData"
      :height="height"
      :max-height="maxHeight"
      :stripe="stripe"
      :border="border"
      :size="size"
      :fit="fit"
      :show-header="showHeader"
      :highlight-current-row="highlightCurrentRow"
      :current-row-key="currentRowKey"
      :row-class-name="rowClassName"
      :row-style="rowStyle"
      :cell-class-name="cellClassName"
      :header-row-class-name="headerRowClassName"
      :header-row-style="headerRowStyle"
      :cell-style="cellStyle"
      :header-cell-class-name="headerCellClassName"
      :header-cell-style="headerCellStyle"
      :row-key="rowKey"
      :empty-text="emptyText"
      :default-expand-all="defaultExpandAll"
      :expand-row-keys="expandRowKeys"
      :default-sort="defaultSort"
      :tooltip-effect="tooltipEffect"
      :show-summary="showSummary"
      :sum-text="sumText"
      :summary-method="summaryMethod"
      :span-method="spanMethod"
      :select-on-indeterminate="selectOnIndeterminate"
      :indent="indent"
      :lazy="lazy"
      :load="load"
      :tree-props="treeProps"
      style="width: 100%"
      v-loading="loading"
      element-loading-background="rgba(255, 255, 255, 0.8)"
      @select="select"
      @select-all="selectAll"
      @selection-change="selectionChange"
      @cell-mouse-enter="cellMouseEnter"
      @cell-click="cellClick"
      @cell-mouse-leave="cellMouseLeave"
      @cell-dblclick="cellDblclick"
      @row-click="rowClick"
      @row-contextmenu="rowContextmenu"
      @row-dblclick="rowDblclick"
      @header-click="headerClick"
      @header-contextmenu="headerContextmenu"
      @filter-change="filterChange"
      @current-change="currentChange"
      @header-dragend="headerDragend"
      :expand-change="expandChange"
      @sort-change="sortChange"
    >
      <el-table-column
        v-if="selection"
        type="selection"
        width="55"
        :align="align"
        :prop="selectionProp"
        :reserve-selection="reserveSelection"
      ></el-table-column>

      <!-- <el-table-column
        v-if="true"
        :cell-class-name="draged-column"
      >
          <li class="infinite-list-item"><i class="el-icon-share"></i></li>
      </el-table-column>
       -->

      <!-- 文本数据渲染 -->
      <template v-for="(item, index) in tableHead || tableCol || []">
        <el-table-column
          v-if="
            slotType.includes(item.columnType) || slotType.includes(item.type) || slotType.includes(colType[item.prop])
          "
          :prop="item.field || item.prop"
          :label="item.label"
          :fixed="item.fixed"
          :column-key="item.columnKey"
          :render-header="item.renderHeader"
          :sort-method="item.sortMethod"
          :sort-by="item.sortBy"
          :sort-orders="item.sortOrders"
          :header-align="item.headerAlign"
          :class-name="item.className"
          :label-class-name="item.labelClassName"
          :selectable="item.selectable"
          :reserve-selection="item.reserveSelection"
          :filters="item.filters"
          :filter-placement="item.filterPlacement"
          :filter-method="item.filterMethod"
          :ffilter-multiple="item.filterMultiple"
          :filtered-value="item.filteredValue"
          :key="item.field"
          :width="item.width"
          :min-width="item.minWidth"
          :align="item.align || align"
          :sortable="item.sortable"
          :resizable="item.resizable"
          :formatter="item.formatter"
          :show-overflow-tooltip="item.showOverflowTooltip"
        >
          <template slot-scope="scope">
            <!-- input输入框组件 type是text/textarea 走这里-->
            <el-input
              v-if="inputType.includes(item.type) || inputType.includes(colType[item.prop])"
              :show-word-limit="item.showWrodLimit"
              :type="item.type || colType[item.prop]"
              :maxlength="item.maxlength"
              :minlength="item.minlength"
              :clearable="item.clearable || true"
              :show-password="item.showPassword"
              :prefix-icon="item.prefixicon"
              :suffix-icon="item.suffixIcon"
              :rows="item.rows"
              :autosize="item.autosize"
              :autocomplete="item.autocomplete"
              :name="item.name"
              :max="item.max"
              :min="item.min"
              :step="item.step"
              :resize="item.resize"
              :autofocus="item.autofocus"
              :form="item.form"
              :tabindex="item.tabindex"
              :validate-event="item.validateEvent"
              :disabled="item.disabled || disabledProp[item.prop] || scope.row.disabled || false"
              :placeholder="item.placeholder || `请输入${item.label}`"
              v-model="scope.row[item.prop]"
              @focus="item.focus && item.focus($event)"
              @blur="item.blur && item.blur($event)"
              @clear="item.clear && item.clear($event)"
              @change="item.change && item.change($event)"
              @input="item.input && item.input($event)"
            ></el-input>
            <!-- select选择器组件 type是select/option 走这里-->

            <el-select
              v-else-if="selectType.includes(item.type) || selectType.includes(colType[item.prop])"
              v-model="scope.row[item.prop]"
              default-first-option
              :clearable="item.clearable || true"
              :disabled="item.disabled || disabledProp[item.prop] || scope.row.disabled || false"
              :remote="item.remote"
              :allow-create="item.allowCreate"
              :multiple="item.multiple"
              :filterable="item.filterable"
              @visible-change="item.visibleChange && item.visibleChange($event)"
              @remove-tag="item.removeTag && item.removeTag($event)"
              @clear="item.clear && item.clear($event)"
              @blur="item.blur && item.blur($event)"
              @focus="item.focus && item.focus($event)"
              @change="item.change && item.change($event)"
              :remote-method="
                item.remoteMethod ||
                ((query) => {
                  remoteMethod(query, item.prop);
                })
              "
              :placeholder="item.placeholder || `请选择${item.label}`"
            >
              <el-option
                v-for="(oItem, okey) in item.option || item.options || item.optionData || optionData[item.prop] || []"
                :key="okey"
                :label="(item.optionProps && oItem[item.optionProps.label]) || oItem.label"
                :value="(item.optionProps && oItem[item.optionProps.value]) || oItem.value"
              >
              </el-option>
            </el-select>

            <div v-else-if="item.type === 'tag'">
              <el-tag
                :type="item.config && item.config.type"
                :closable="item.config && item.config.closable"
                :hit="item.config && item.config.hit"
                @click="item.config && item.config.click(scope)"
                @close="item.config && item.config.close(scope)"
                style="margin: 0 5px 5px 0"
                v-for="(tag, index) in scope.row[item.prop] && scope.row[item.prop].split(',')"
                :key="index"
              >
                {{ tag }}</el-tag
              >
            </div>

            <!-- 插槽 type是slot 走这里-->
            <slot v-else :name="item.slotName || item.field || item.prop" :data="scope" />
          </template>
          <!-- <template v-slot="scope" v-else>
            <slot :name="item.slotName || item.field || item.prop" :data="scope" />
          </template> -->
        </el-table-column>
        <!-- 操作 type是operation 走这里-->
        <el-table-column
          :width="item.width"
          :label="item.label"
          :fixed="item.fixed || 'right'"
          :align="item.align || align"
          v-else-if="item.type === 'operation' || item.prop === 'operation'"
          :key="index"
        >
          <template v-slot="scope">
            <el-button
              v-for="(child, cIndex) in item.children"
              :icon="child.icon"
              :class="child.class"
              :type="child.type || 'text'"
              :key="cIndex"
              v-show="!(child.hide && child.hide(scope))"
              :disabled="
                (child.disabled && (typeof child.disabled == 'boolean' ? child.disabled : child.disabled(scope))) ||
                item.disabled ||
                (item.disabledIndex && item.disabledIndex.includes(scope.$index))
              "
              :circle="child.circle || item.circle"
              :round="child.round || item.round"
              :plain="child.plain || item.plain"
              @click="child.click && child.click(scope)"
            >
              {{
                typeof child.title == "function"
                  ? child.title(scope)
                  : child.title || typeof child.label == "function"
                  ? child.label(scope)
                  : child.label
              }}</el-button
            >
          </template>
        </el-table-column>
        <!-- 默认情况 -->
        <el-table-column
          v-else
          :prop="item.field || item.prop"
          :label="item.label"
          :fixed="item.fixed"
          :column-key="item.columnKey"
          :render-header="item.renderHeader"
          :sort-method="item.sortMethod"
          :sort-by="item.sortBy"
          :sort-orders="item.sortOrders"
          :header-align="item.headerAlign"
          :class-name="item.className"
          :label-class-name="item.labelClassName"
          :selectable="item.selectable"
          :reserve-selection="item.reserveSelection"
          :filters="item.filters"
          :filter-placement="item.filterPlacement"
          :filter-method="item.filterMethod"
          :ffilter-multiple="item.filterMultiple"
          :filtered-value="item.filteredValue"
          :key="item.field"
          :width="item.width"
          :align="item.align || align"
          :sortable="item.sortable"
          :resizable="item.resizable"
          :formatter="item.formatter"
          :show-overflow-tooltip="item.showOverflowTooltip"
        ></el-table-column>
      </template>
    </el-table>
    <slot></slot>
  </div>
</template>

<script>
export default {
  name: "secTable",
  components: {},
  props: {
    //仅对 type=selection 的列有效，类型为 Boolean，为 true 则会在数据更新之后保留之前选中的数据（需指定 row-key）
    reserveSelection: Boolean,
    selectionProp: String, //type:selection 的prop属性
    height: [String, Number],
    maxHeight: [String, Number],
    border: {
      type: Boolean,
      default: () => {
        return false;
      },
    },
    stripe: {
      type: Boolean,
      default: false,
    },
    size: String,
    fit: {
      type: Boolean,
      default: true,
    },
    showHeader: {
      type: Boolean,
      default: true,
    },
    highlightCurrentRow: {
      type: Boolean,
      default: false,
    },
    rowClassName: Function,
    rowStyle: Function,
    // cellStyle: Function,
    headerRowClassName: Function,
    headerRowStyle: Function,
    headerCellClassName: Function,
    // headerCellStyle: Function,
    rowKey: Function,
    emptyText: String,
    defaultExpandAll: {
      type: Boolean,
      default: false,
    },
    expandRowKeys: Array,
    defaultSort: Object,
    tooltipEffect: String,
    showSummary: Boolean,
    sumText: String,
    summaryMethod: Function,
    spanMethod: Function,
    selectOnIndeterminate: Boolean,
    indent: Number,
    lazy: Boolean,
    load: Function,
    treeProps: Object,
    currentRowKey: [String, Number],
    cellClassName: Function,
    selection: {
      type: Boolean,
      default: false,
    },
    pagination: {
      type: Object,
      default: () => {
        return null;
      },
    },
    optionData: {
      type: Object,
      default: () => {
        return {};
      },
    },
    disabledProp: {
      //让哪个form表单disabled 例如  disabledProp:{name:true} 让字段为name的表单失效
      type: Object,
      default: () => {
        return {};
      },
    },
    // 行的类型
    colType: {
      type: Object,
      default: () => {
        return {};
      },
    },
    loading: {
      type: Boolean,
      default: false,
    },
    tableData: Array,
    tableCol: Array,
    tableHead: Array,
    redSign: Array,
    align: {
      type: String,
      default: "left",
    },
    showList: Number,
  },
  data() {
    return {
      slotType: ["slot", "select", "option", "text", "textarea", "tag"],
      selectType: ["select", "option"],
      inputType: ["text", "textarea"],
    };
  },
  mounted() {},
  methods: {
    //用于多选表格，切换某一行的选中状态，如果使用了第二个参数，则是设置这一行选中与否（selected 为 true 则选中）
    toggleRowSelection(row, selected) {
      this.$refs.multipleTable.toggleRowSelection(row, selected);
    },
    //用于多选表格，清空用户的选择
    clearSelection() {
      this.$refs.multipleTable.clearSelection();
    },
    //当用户手动勾选数据行的 Checkbox 时触发的事件
    select(selection, row) {
      this.$emit("select", selection, row);
    },
    //当用户手动勾选全选 Checkbox 时触发的事件
    selectAll(selection) {
      this.$emit("selectAll", selection);
      this.$emit("select-all", selection);
    },
    // 当选择项发生变化时会触发该事件
    selectionChange(selection) {
      this.$emit("selectionChange", selection);
    },
    //当单元格 hover 进入时会触发该事件
    cellMouseEnter(row, column, cell, event) {
      this.$emit("cellMouseEnter", row, column, cell, event);
    },
    //当单元格 hover 退出时会触发该事件
    cellMouseLeave(row, column, cell, event) {
      this.$emit("cellMouseLeave", row, column, cell, event);
    },
    //当某个单元格被点击时会触发该事件
    cellClick(row, column, cell, event) {
      this.$emit("cellClick", row, column, cell, event);
    },
    //当某个单元格被双击击时会触发该事件
    cellDblclick(row, column, event) {
      this.$emit("cellDblclick", row, column, event);
    },
    //当某一行被点击时会触发该事件
    rowClick(row, column, event) {
      this.$emit("rowClick", row, column, event);
    },
    //当某一行被鼠标右键点击时会触发该事件
    rowContextmenu(row, column, event) {
      this.$emit("rowContextmenu", row, column, event);
    },
    //当某一行被双击时会触发该事件
    rowDblclick(row, column, event) {
      this.$emit("rowDblclick", row, column, event);
    },
    //当某一列的表头被点击时会触发该事件
    headerClick(column, event) {
      this.$emit("headerClick", column, event);
    },
    //当某一列的表头被鼠标右键点击时触发该事件
    headerContextmenu(column, event) {
      this.$emit("headerContextmenu", column, event);
    },
    //当表格的排序条件发生变化的时候会触发该事件
    sortChange(column, prop, order) {
      this.$emit("sortChange", { column, prop, order });
    },
    //当表格的筛选条件发生变化的时候会触发该事件，参数的值是一个对象，对象的 key 是 column 的 columnKey，对应的 value 为用户选择的筛选条件的数组。
    filterChange(filters) {
      this.$emit("filterChange", filters);
    },
    //当表格的当前行发生变化的时候会触发该事件，如果要高亮当前行，请打开表格的 highlight-current-row 属性
    currentChange(currentRow, oldCurrentRow) {
      this.$emit("currentChange", currentRow, oldCurrentRow);
    },
    //当拖动表头改变了列的宽度的时候会触发该事件
    headerDragend(newWidth, oldWidth, column, event) {
      this.$emit("headerDragend", newWidth, oldWidth, column, event);
    },
    //当用户对某一行展开或者关闭的时候会触发该事件（展开行时，回调的第二个参数为 expandedRows；树形表格时第二参数为 expanded）
    expandChange(row, expandedRows) {
      this.$emit("expandChange", row, expandedRows);
    },
    headerCellStyle() {
      return "background: #fafafa;color: #333;";
    },

    cellStyle({ row, column, rowIndex, columnIndex }) {
      if (column.label === "备注" && this.redSign && this.redSign.includes(row.sign)) {
        return "color:red";
      }
      if (column.label === "执行方式") {
        if (row.hit_action === "break") {
          return "color:red";
        } else if (row.hit_action === "continue") {
          return "color:green";
        }
      }
      if (column.label === "策略状态") {
        //open, observe, close
        let ruleStatus = row.status;
        if (ruleStatus) {
          if (ruleStatus == "close") {
            return "color:red";
          }
          if (ruleStatus == "open") {
            return "color:green";
          }
          if (ruleStatus == "observe") {
            return "color:orange";
          }
          return "color:";
        }
      }
    },
  },

  computed: {},
  watch: {
    tableData: {
      deep: true,
      immediate: true,
      handler(newVal) {
        this.$nextTick(() => {
          newVal &&
            newVal.forEach((item) => {
              if (item.selected_flag) {
                this.$refs.multipleTable.toggleRowSelection(item);
              }
            });
        });
      },
    },
  },
};
</script>
<style lang="scss" scoped>
.table-box {
  position: relative;
  .see-more {
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translate(-50%, 50%);
    z-index: 100;
  }
}
</style>
